<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="search">
        <el-form ref="queryFormRef" :inline="true" :model="queryParams" label-width="68px">
          <el-form-item label="小区ID" prop="extCommunityId">
            <el-input v-model="queryParams.extCommunityId" clearable placeholder="请输入小区ID" style="width: 240px" @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item label="小区名称" prop="name">
            <el-input v-model="queryParams.name" clearable placeholder="请输入小区名称" style="width: 240px" @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item label="小区地址" prop="address">
            <el-input v-model="queryParams.address" clearable placeholder="请输入小区地址" style="width: 240px" @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item>
            <el-button icon="Search" type="primary" @click="handleQuery">搜索</el-button>
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button v-hasPermi="['system:community:add']" icon="Plus" plain type="primary" @click="handleAdd">新增 </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button v-hasPermi="['system:community:edit']" :disabled="single" icon="Edit" plain type="success" @click="handleUpdate()"
              >修改
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button v-hasPermi="['system:community:remove']" :disabled="multiple" icon="Delete" plain type="danger" @click="handleDelete()"
              >删除
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button v-hasPermi="['system:community:export']" icon="Download" plain type="warning" @click="handleExport">导出 </el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" :data="communityList" @selection-change="handleSelectionChange">
        <el-table-column align="center" type="selection" width="55" />
        <el-table-column v-if="true" align="center" label="小区ID" prop="communityId" />
        <el-table-column align="center" label="小区名称" prop="name" />
        <el-table-column align="center" label="小区地址" prop="address" />
        <el-table-column align="center" label="客服电话" prop="tel" />
        <el-table-column align="center" label="外部编码" prop="extCommunityId" />
        <el-table-column align="center" label="备注" prop="remark" />
        <el-table-column align="center" class-name="small-padding fixed-width" label="操作">
          <template #default="scope">
            <el-tooltip content="修改" placement="top">
              <el-button v-hasPermi="['system:community:edit']" icon="Edit" link type="primary" @click="handleUpdate(scope.row)"></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button v-hasPermi="['system:community:remove']" icon="Delete" link type="primary" @click="handleDelete(scope.row)"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total>0" v-model:limit="queryParams.pageSize" v-model:page="queryParams.pageNum" :total="total" @pagination="getList" />
    </el-card>
    <!-- 添加或修改小区对话框 -->
    <el-dialog v-model="dialog.visible" :title="dialog.title" append-to-body width="500px">
      <el-form ref="communityFormRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="小区名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入小区名称" />
        </el-form-item>
        <el-form-item label="小区地址" prop="address">
          <checkAddress v-model="address" :form="address" />
        </el-form-item>
        <el-form-item label="客服电话" prop="tel">
          <el-input v-model="form.tel" placeholder="请输入联系方式" />
        </el-form-item>
        <el-form-item label="外部编码" prop="extCommunityId">
          <el-input v-model="form.extCommunityId" placeholder="请输入外部编码" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" name="Community" setup>
import checkAddress from "@/components/checkAddress/index.vue";
import { addCommunity, delCommunity, getCommunity, listCommunity, updateCommunity } from "@/api/system/community";
import { CommunityForm, CommunityQuery, CommunityVO } from "@/api/system/community/types";

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const communityList = ref<CommunityVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);

const queryFormRef = ref<ElFormInstance>();
const communityFormRef = ref<ElFormInstance>();

const dialog = reactive<DialogOption>({
  visible: false,
  title: ""
});

const initFormData: CommunityForm = {
  communityId: undefined,
  name: undefined,
  address: undefined,
  cityCode: undefined,
  tel: undefined,
  extCommunityId: undefined,
  lat: undefined,
  lng: undefined,
  status: undefined,
  remark: undefined
};

const address: any = ref({
  // 省
  province: "",
  // 市
  city: "",
  // 区
  district: "",
  //详细地址
  detail: "",
  cityCode: ""
});
const data = reactive<PageData<CommunityForm, CommunityQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    name: undefined,
    address: undefined,
    cityCode: undefined,
    tel: undefined,
    extCommunityId: undefined,
    lat: undefined,
    lng: undefined,
    status: undefined,
    params: {}
  },
  rules: {
    communityId: [
      { required: true, message: "小区ID不能为空", trigger: "blur" }
    ],
    name: [
      { required: true, message: "小区名称不能为空", trigger: "blur" }
    ],
    address: [
      { required: true, message: "小区地址不能为空", trigger: "blur" }
    ],
    cityCode: [
      { required: true, message: "根据定位获取城市编码不能为空", trigger: "blur" }
    ],
    tel: [
      { required: true, message: "联系方式不能为空", trigger: "blur" }
    ],
    extCommunityId: [
      { required: true, message: "外部编码不能为空", trigger: "blur" }
    ],
    lat: [
      { required: true, message: "经度不能为空", trigger: "blur" }
    ],
    lng: [
      { required: true, message: "纬度不能为空", trigger: "blur" }
    ],
    status: [
      { required: true, message: "状态不能为空", trigger: "change" }
    ],
    remark: [
      { required: true, message: "备注不能为空", trigger: "blur" }
    ]
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询小区列表 */
const getList = async () => {
  loading.value = true;
  const res = await listCommunity(queryParams.value);
  communityList.value = res.rows;
  total.value = res.total;
  loading.value = false;
};

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
};

/** 表单重置 */
const reset = () => {
  form.value = { ...initFormData };
  communityFormRef.value?.resetFields();
};

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
};

/** 多选框选中数据 */
const handleSelectionChange = (selection: CommunityVO[]) => {
  ids.value = selection.map(item => item.communityId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
};

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  dialog.visible = true;
  dialog.title = "添加小区";
};

/** 修改按钮操作 */
const handleUpdate = async (row?: CommunityVO) => {
  reset();
  const _communityId = row?.communityId || ids.value[0];
  const res = await getCommunity(_communityId);
  Object.assign(form.value, res.data);
  dialog.visible = true;
  dialog.title = "修改小区";
  let split: any = form.value.address?.split("/");
  address.value = {
    province: split[0],
    city: split[1],
    district: split[2],
    detail: split[3],
    cityCode: form.value.cityCode
  };
};

/** 提交按钮 */
const submitForm = () => {
  communityFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.communityId) {
        await updateCommunity(form.value).finally(() => buttonLoading.value = false);
      } else {
        await addCommunity(form.value).finally(() => buttonLoading.value = false);
      }
      proxy?.$modal.msgSuccess("修改成功");
      dialog.visible = false;
      await getList();
    }
  });
};

/** 删除按钮操作 */
const handleDelete = async (row?: CommunityVO) => {
  const _communityIds = row?.communityId || ids.value;
  await proxy?.$modal.confirm("是否确认删除小区编号为\"" + _communityIds + "\"的数据项？").finally(() => loading.value = false);
  await delCommunity(_communityIds);
  proxy?.$modal.msgSuccess("删除成功");
  await getList();
};

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download("system/community/export", {
    ...queryParams.value
  }, `community_${new Date().getTime()}.xlsx`);
};

onMounted(() => {
  getList();
});
watch(address.value, (val) => {
  form.value.address = val.province + "/" + val.city + "/" + val.district + "/" + val.detail;
  form.value.cityCode = val.cityCode;
});
</script>
